package com.exonline.back.controller.login;

import com.exonline.commons.entity.Manager;
import com.exonline.commons.entity.Menu;
import com.exonline.commons.dao.DaoImpl;
import com.exonline.commons.dao.IDao;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 *    @desc 管理员登录模块M层
 * - `login`方法获取用户的姓名、角色信息，并返回动态菜单。
 * - `register`方法实现用户注册功能。
 * - `loginWithUserName`方法通过用户名（手机号）登录，获取用户的菜单。
 *
 * @author hbrj
 */
public class LoginService {

    // 引入数据访问对象
    IDao<Object> loginDao = new DaoImpl();

    /**
     * @desc 1.登录并根据用户名和密码查询管理员信息并返回用户的菜单。
     * @param name 用户名（例如手机号）
     * @param password 用户密码
     * @return 登录成功返回管理员信息及菜单，失败返回null
     * @throws SQLException 数据库异常
     */
    public Object login(String name, String password) throws SQLException {
        // 1.1查询管理员信息,获取管理员(Manager)对象
        Manager manager = loginDao.queryForObject(
                "SELECT r.id as rid, a.id, a.aname, r.rname FROM admin a JOIN userrole ur on ur.aid = a.id JOIN role r on r.id = ur.rid WHERE aname = ? and password = ?",
                new BeanHandler<>(Manager.class),
                name, password
        );

        // 1.1查询用户的菜单,并存入用户对象
        if (manager == null) {
            return null;  // 1.2校验用户是否存在于数据库
        } else {
            // 1.2根据该用户所属角色查询父级菜单
            List<Menu> parentMenus = loginDao.queryForObject(
                    "SELECT DISTINCT m.id AS id, m.mname AS mname, m.murl AS murl, m.mparent AS mparent FROM menu m JOIN rolemenu rm on rm.mid = m.id JOIN role r on r.id = rm.rid JOIN userrole ur on ur.rid = r.id JOIN admin a on a.id = ur.aid WHERE a.id = ? AND m.mparent IS NULL",
                    new BeanListHandler<>(Menu.class),
                    manager.getId()
            );

            // 1.3根据该用户所属角色查询子级菜单
            List<Menu> subMenus = loginDao.queryForObject(
                    "SELECT DISTINCT m.id AS id, m.mname AS mname, m.murl AS murl, m.mparent AS mparent FROM menu m JOIN rolemenu rm on rm.mid = m.id JOIN role r on r.id = rm.rid JOIN userrole ur on ur.rid = r.id JOIN admin a on a.id = ur.aid WHERE a.id = ? AND m.mparent IS NOT NULL",
                    new BeanListHandler<>(Menu.class),
                    manager.getId()
            );

            //1.4将子级菜单加入到对应的父级菜单下
            for (Menu parentMenu : parentMenus) {
                String parentId = parentMenu.getId();
                for (Menu subMenu : subMenus) {
                    if (subMenu.getMparent().equals(parentId)) {
                        parentMenu.addSubMenus(subMenu);
                    }
                }
            }

            //1.5将获取到的角色菜单装入manager对象
            manager.setMenus(parentMenus);
            //1.6更新管理员的最后登录时间
            loginDao.updateWithTransaction("UPDATE admin SET lastlogintime = CURRENT_TIMESTAMP WHERE id = ?", manager.getId());
            return manager;
        }
    }
}
